import { putAddress, queryAddress, queryProfileInfo, queryPwdStrength } from '@/api/setApi'
import { UpdatePwdFormDataProps } from '@/components/UpdatePassword/interface'
import { UserInfoProps } from '@/utils/interface'
import { transPwdStrength, transUserInfo } from '@/utils/translator'
import { useContext, useEffect, useRef, useState } from 'react'
import { TabDataProps } from '../interface'
import { AppContext } from '@/pages/App/context'
import { useLocation, useNavigate } from 'react-router-dom'
import { UpdateAddressFormDataProps } from '@/components/UpdateAddress/interface'
import { transAddress } from '../translator'
import { alertModal, confirmModal } from '@/components/Modal'
// import { checkIsIP, checkMac, toFullIPV6Addr, checkIsExistSelfIP } from '@/utils/rules'
import { UpdatePINFormDataProps } from '@/components/UpdatePIN/interface'
import { OBJECT_NAME } from '@/utils/common'
import { Message } from '@kedacom/react-next'
// import ipaddr from 'ipaddr.js'
// import { Modal } from '@kedacom/react-next'
const useIndexHook = () => {
	//window.location.hash  # profile 个人设置  #portrait 头像 #password 密码
	const [tabValue, setTabValue] = useState<string>('')
	const [passwordStrength, setPasswordStrength] = useState<number>(0)
	const AppData = useContext(AppContext)
	const userInfo = AppData.user
	const systemInfo = AppData.system
	const profileRef = useRef<any>() //个人信息
	const pwdRef = useRef<any>() //修改密码
	const ipRef = useRef<any>() //修改IP地址
	const pinRef = useRef<any>() //修改PIN码
	const [saveDisabled, setSaveDisabled] = useState(false)
	/**是否展示：密码修改后，需使用新密码重新登录，请牢记新密码！ */
	const [isShowRememberNewPwd, setIsShowRememberNewPwd] = useState<boolean>(true)
	const [profileInfo, setProfileInfo] = useState<UserInfoProps>()
	const [addressFormData, setAddressFormData] = useState<UpdateAddressFormDataProps[]>([])
	// const [newAddressFormData, setNewAddressFormData] = useState<UpdateAddressFormDataProps[]>([])
	const [tabData, setTabData] = useState<TabDataProps[]>([])
	const navigate = useNavigate()
	const location = useLocation()
	useEffect(() => {
		if (location) {
			setTabValue(location.pathname)
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [location])
	useEffect(() => {
		if (userInfo.moid && systemInfo.systemSecurityLevel !== undefined) {
			if (systemInfo.systemSecurityLevel === 3) {
				setTabData([
					// { text: '个人信息', value: '/set/profile' },
					{ text: '修改PIN码', value: '/set/pin' },
					{ text: '用户绑定终端策略', value: '/set/ip' },
				])
			} else {
				/**获取要设置的密码强度 */
				getPwdStrength()
				setTabData([
					// { text: '个人信息', value: '/set/profile' },
					{ text: '修改密码', value: '/set/password' },
					{ text: '用户绑定终端策略', value: '/set/ip' },
				])
			}
			getAddress()
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [userInfo.moid, systemInfo.systemSecurityLevel])
	useEffect(() => {
		//tab在修改密码下 默认 保存按钮禁用  其他tab下默认开放保存按钮
		//tab切换时校验内容已改变
		if (tabValue === '/set/password') {
			// madeConfirmTipBySuper()
			setSaveDisabled(true)
			setIsShowRememberNewPwd(false)
		} else if (tabValue === '/set/pin') {
			setSaveDisabled(true)
		} else if (tabValue === '/set/ip') {
			if (userInfo.moid) {
				getAddress()
			}
			setSaveDisabled(false)
		} else {
			setSaveDisabled(false)
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [tabValue])
	/**切换到修改密码tab下，要做提示 */
	// const madeConfirmTipBySuper = () => {
	// 	confirmModal({
	// 		msg: '密码修改后，请牢记新密码！ 未配置邮箱将密码丢失后无法找回，需返厂进行初始化',
	// 		okText: '重置密码',
	// 		onOk: () => {
	// 			setIsShowRememberNewPwd(true)
	// 		},
	// 		onCancel: () => {
	// 			onCancel()
	// 		},
	// 	})
	// }
	/**取消按钮 */
	const onCancel = () => {
		navigate(`/home`)
	}

	/**获取密码强度 */
	const getPwdStrength = () => {
		let dataJson = {
			moid: userInfo.moid,
		}
		queryPwdStrength(dataJson).then((res: { data: any }) => {
			// 密码强度 1-弱 2-中 3-强
			let data = res.data
			data = transPwdStrength(data)
			setPasswordStrength(data.passwordStrength)
		})
	}
	/**
	 * 点击tab时
	 * @param item 点击的tab值
	 *
	 */
	const onTabClick = (item: TabDataProps) => {
		if (item.value !== tabValue) {
			let toTarget = item.value //切换到的目标页面
			navigate(`${toTarget}`)
		}
	}
	/**获取IP，Mac地址 */
	const getAddress = () => {
		// let dataJson = {
		// 	moid: userInfo.moid,
		// }
		queryAddress().then((res: any) => {
			let data = res.data
			if (data && data.length !== 0) {
				data = transAddress(data)
			}
			setAddressFormData(data)
		})
	}
	/**修改，添加新ip mac，更新数据 */
	// const onUpdateIPChange = (formData: UpdateAddressFormDataProps[]) => {
	// 	setNewAddressFormData(formData)
	// }
	// const isExistSelfIP = (resetList: any) => {
	// 	return new Promise((resolve, reject) => {
	// 		if (checkIsExistSelfIP(resetList)) {
	// 			resolve(true)
	// 		} else {
	// 			let m = Modal.confirm({
	// 				content: <div>绑定的IP&MAC地址中，不存在操作终端地址，是否继续保存？</div>,
	// 				onOk: () => {
	// 					resolve(true)
	// 					m.hide()
	// 				},
	// 				onCancel: () => {
	// 					reject(false)
	// 					m.hide()
	// 				},
	// 			})
	// 		}
	// 	})
	// }
	/**ip mac校验 */
	// const checkIpMac = () => {
	// 	let rule = true
	// 	for (var index = 0; index < newAddressFormData.length; index++) {
	// 		let item = newAddressFormData[index]
	// 		if (!item.ip || !item.mac) {
	// 			alertModal({
	// 				msg: 'IP,MAC需全部填写',
	// 			})
	// 			rule = false
	// 			break
	// 		}
	// 		if (!checkIsIP(item.ip)) {
	// 			alertModal({
	// 				msg: 'IP地址填写错误',
	// 			})
	// 			rule = false
	// 			break
	// 		}
	// 		if (!checkMac(item.mac)) {
	// 			alertModal({
	// 				msg: 'MAC地址填写错误',
	// 			})
	// 			rule = false
	// 			break
	// 		}
	// 		/**唯一性校验，ip+mac为一条数据，不可重复 */
	// 		for (var j = index + 1; j < newAddressFormData.length; j++) {
	// 			if (
	// 				toFullIPV6Addr(item.ip) === toFullIPV6Addr(newAddressFormData[j].ip) &&
	// 				item.mac.replace(/-/g, ':').toUpperCase() ===
	// 					newAddressFormData[j].mac.replace(/-/g, ':').toUpperCase()
	// 			) {
	// 				alertModal({
	// 					msg: '请勿重复添加数据',
	// 				})
	// 				rule = false
	// 				break
	// 			}
	// 		}
	// 	}
	// 	return rule
	// }
	// const onSaveIpData = async () => {
	// 	let checkRules = checkIpMac()
	// 	if (!checkRules) {
	// 		return false
	// 	}
	// 	let resetList: { ip: string; mac: string }[] = []
	// 	newAddressFormData.forEach((item) => {
	// 		resetList.push({ ip: toFullIPV6Addr(item.ip) || '', mac: item.mac.replace(/-/g, ':').toUpperCase() })
	// 	})
	// 	let checkStatus = await isExistSelfIP(resetList).catch(() => {
	// 		return false
	// 	})
	// 	if (!checkStatus) {
	// 		return false
	// 	}
	// 	//发送请求
	// 	let dataJson = {
	// 		moid: userInfo.moid,
	// 		lists: resetList,
	// 	}
	// 	putAddress(dataJson).then((res: any) => {
	// 		// 弹出框
	// 		alertModal({
	// 			msg: '保存成功',
	// 			onOk: () => {
	// 				getAddress()
	// 			},
	// 		})
	// 	})
	// }
	// useEffect(() => {}, [newAddressFormData])
	/**修改密码组件，更新数据时 */
	const onUpdatePwdChange = (formData: UpdatePwdFormDataProps) => {
		let result = formData.currentPwdCheck && formData.newPwdCheck && formData.confirmPwdCheck
		let isDisabled = result ? false : true
		setSaveDisabled(isDisabled)
	}
	/**修改PIN组件，更新数据 */
	const onUpdatePINChange = (formData: UpdatePINFormDataProps) => {
		let result = formData.currentPINCheck && formData.newPINCheck && formData.confirmPINCheck
		let isDisabled = result ? false : true
		setSaveDisabled(isDisabled)
	}
	/**点击保存按钮 */
	const onSave = () => {
		let currentKeyName = tabValue //当前所在页面
		saveData(currentKeyName)
	}
	/**
	 * 保存当前form表单信息
	 * @param tabKeyName 当前tab
	 */
	const saveData = (tabKeyName: string) => {
		switch (tabKeyName) {
			case '/set/profile': //个人信息
				profileRef.current && profileRef.current.saveData()
				break
			case '/set/password': //修改密码页面
				pwdRef.current && pwdRef.current.saveData()
				break
			case '/set/pin': //修改PIN码页面
				pinRef.current && pinRef.current.saveData()
				break
			case '/set/ip': //修改IP地址页面
				// onSaveIpData()
				// ipRef.current && ipRef.current.saveData()
				break
		}
	}
	const selectAddress = (
		/**操作后所有ip，mac数据 */
		resetList: [{ ip: string; mac: string }],
		/**操作类型 add/del */
		type: string,
		/**增删的数组 */
		list: { ip: string; mac: string; key?: string }[]
	) => {
		let dataJson = {
			moid: userInfo.moid,
			lists: resetList,
		}
		let _e = null
		let _o = null
		if (type === 'add') {
			for (let k = 0; k < list.length; k++) {
				_e = ''
				_e += '添加ip“' + list[k].ip + '”,mac“' + list[k].mac + '”'
			}
		} else if (type === 'del') {
			_e = ''
			_e += '删除ip“' + list[0].ip + '”,mac“' + list[0].mac + '”'
		}
		_e = _e ? encodeURIComponent('安全审计员' + _e) : _e
		_o = encodeURIComponent(OBJECT_NAME)
		putAddress({ ...dataJson, _e, _o }).then((res: any) => {
			Message.info(type === 'del' ? '删除成功' : '保存成功')
			getAddress()
		})
	}
	return {
		tabValue,
		saveDisabled,
		tabData,
		onTabClick,
		profileRef,
		pwdRef,
		ipRef,
		pinRef,
		onSave,
		userInfo,
		profileInfo,
		passwordStrength,
		onCancel,
		isShowRememberNewPwd,
		onUpdatePwdChange,
		onUpdatePINChange,
		addressFormData,
		// newAddressFormData,
		// onUpdateIPChange,
		selectAddress,
	}
}
export default useIndexHook
